package GUI.view;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

import GUI.models.TreeNodeImplProperties;
import GUI.view.Calendar.MyCalen;

import client.domainModels.Node.Node;
import client.domainModels.NodeImpl.AbstractNode;

/**
 * 
 * @author Wei WANG
 */
public class TreeConfAddPanelFormule extends JPanel implements ActionListener,
		FocusListener {
	CombBoxHistory streetField, cityField;
	CombBoxHistory zipField;
	JComponent[] fields;
	JPanel tablesPanel;

	static int eventID = 0;

	boolean addressSet = false;
	final static int GAP = 10;
	XMLFileTree tree;
	JPanel leftHalf;
	String[] nodeLabels;
	AbstractNode currentNode;

	public TreeConfAddPanelFormule(XMLFileTree tree, JPanel tablesPanel) {
		this.tree = tree;
		this.tablesPanel = tablesPanel;

		currentNode = tree.getLastNode().getPropretiesObj();
		nodeLabels = currentNode.getChildNodeNames();

		fields = new JComponent[nodeLabels.length];
		setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));

		leftHalf = new JPanel() {
			// Don't allow us to stretch vertically.
			public Dimension getMaximumSize() {
				Dimension pref = getPreferredSize();
				return new Dimension(Integer.MAX_VALUE, pref.height);
			}
		};
		leftHalf.setLayout(new BoxLayout(leftHalf, BoxLayout.PAGE_AXIS));
		if (nodeLabels[0].equals("Event")) {
			leftHalf.add(createLabels("Add an Event?"));
		} else {
			leftHalf.add(createEntryFields());
		}

		leftHalf.add(createButtons());

		add(leftHalf);

	}

	protected JComponent createButtons() {
		JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));

		JButton button = new JButton("Set");
		button.addActionListener(this);
		panel.add(button);

		/*
		 * button = new JButton("Clear"); button.addActionListener(this);
		 * button.setActionCommand("clear"); panel.add(button);
		 */

		// Match the SpringLayout's gap, subtracting 5 to make
		// up for the default gap FlowLayout provides.
		panel.setBorder(BorderFactory.createEmptyBorder(0, 0, GAP - 5, GAP - 5));
		return panel;
	}

	protected JComponent createLabels(String id) {
		JPanel panel = new JPanel(new BorderLayout());
		JLabel labels = new JLabel();
		labels.setText(id);
		panel.add(labels, BorderLayout.CENTER);
		return panel;

	}

	public AbstractNode createNodeInstance(String s) {
		Class eventclass;
		AbstractNode instance = null;
		try {
			eventclass = Class.forName("client.domainModels.NodeImpl." + s);
			instance = (AbstractNode) eventclass.newInstance();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return instance;
	}

	/**
	 * Called when the user clicks the button or presses Enter in a text field.
	 */
	public void actionPerformed(ActionEvent e) {
		// tree.removeCurrentNodeChildren();

		// addressSet = true;
		for (int i = 0; i < nodeLabels.length; i++) {
			Class eventclass;
			AbstractNode instance;
			instance = createNodeInstance(nodeLabels[i]);

			if (nodeLabels[0].equals("Event")) {
				eventID += 1;
				instance.setID("Event" + eventID);
			} else if (nodeLabels[i].equals("TimeStamp")) {
				instance.setID(((MyCalen) fields[i]).getDate().getText());
			} else if (nodeLabels[i].equals("Receivers")) {
				instance.setID(" ");
			} else {
				instance.setID(((CombBoxHistory) fields[i]).getItemSelected());
				instance.addRecordInHistory(((CombBoxHistory) fields[i]).getItemSelected());
			}
			
			if (tree != null){
				if(currentNode.getClass().getSimpleName().equals("Event")&&tree.getLastNode().getChildCount()>=6){	
				
				}else{
					tree.addObject(instance);
				}	
			}
			JScrollPane scrollPanel = new JScrollPane(
					MultiLineTableConstructor.createLogTable(tree.getRootNode()));
			tablesPanel.removeAll();
			tablesPanel.add(scrollPanel, BorderLayout.CENTER);
			tablesPanel.updateUI();
		}
	}

	/**
	 * Called when one of the fields gets the focus so that we can select the
	 * focused field.
	 */
	public void focusGained(FocusEvent e) {
		Component c = e.getComponent();
		if (c instanceof JFormattedTextField) {
			selectItLater(c);
		} else if (c instanceof JTextField) {
			((JTextField) c).selectAll();
		}
	}

	// Workaround for formatted text field focus side effects.
	protected void selectItLater(Component c) {
		if (c instanceof JFormattedTextField) {
			final JFormattedTextField ftf = (JFormattedTextField) c;
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					ftf.selectAll();
				}
			});
		}
	}

	// Needed for FocusListener interface.
	public void focusLost(FocusEvent e) {
	} // ignore

	public void desactiveReceiverAndConversation() {
		for (int i = 0; i < nodeLabels.length; i++) {
			String label = nodeLabels[i];
			if (label.equals("Conversation")) {
				((CombBoxHistory) fields[i]).desactive();
			} else if (label.equals("Receivers")) {
				((JLabel) fields[i]).setText("Desactive");
			}
		}
		this.updateUI();
	}

	protected JComponent createEntryFields() {
		AbstractNode currentNode = tree.getLastNode().getPropretiesObj();
		String[] nodeLabels = currentNode.getChildNodeNames();

		JPanel panel = new JPanel(new SpringLayout());
		JLabel[] labels = new JLabel[nodeLabels.length];

		int fieldNum = 0;
		String[] sList = {};
		for (int i = 0; i < nodeLabels.length; i++) {
			if (nodeLabels[i].equals("TimeStamp")) {
				JPanel textField = new MyCalen();
				fields[fieldNum++] = textField;
			} else if (nodeLabels[i].equals("Receivers")) {
				JLabel textField = new JLabel("Genere automatique");
				fields[fieldNum++] = textField;
			} else {
				AbstractNode nodeTmp = createNodeInstance(nodeLabels[i]);
				CombBoxHistory textField = new CombBoxHistory(nodeTmp
						.getHistoryList().toArray(), this);
				fields[fieldNum++] = textField;
			}
		}

		// Associate label/field pairs, add everything,
		// and lay it out.
		for (int i = 0; i < nodeLabels.length; i++) {
			labels[i] = new JLabel(nodeLabels[i], JLabel.TRAILING);
			labels[i].setLabelFor(fields[i]);
			panel.add(labels[i]);
			panel.add(fields[i]);

			// Add listeners to each field
			fields[i].addFocusListener(this);
		}
		SpringUtilities.makeCompactGrid(panel, nodeLabels.length, 2, GAP, GAP, // init
																				// x,y
				GAP, GAP / 2);// xpad, ypad
		return panel;
		
	}
}
